package com.example.web.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.democommon.tools.Result;
import com.example.demodao.entity.TbInfo;
import com.example.demodao.mapper.TbInfoMapper;
import com.example.service.TbInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cursor.Cursor;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author rosszhang
 * @since 2023-02-24
 */
@Slf4j
@RestController
@RequestMapping("/info")
public class TbInfoController {

    @Autowired
    private TbInfoService tbInfoService;
    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @GetMapping("/addInfo")
    public void addInfo() {
        tbInfoService.addInfo();
    }

    /*-------------------------------------------优美的分割线-----------------------------------------------------------*/
    /*开始测试Mybatis的流式查询*/

    /**
     * 方案一：SqlSessionFactory 来手工打开数据库连接
     */
    @GetMapping("/getInfo")
    public Result<?> getInfo(@RequestParam(name = "limit") int limit) throws Exception {
        // 打开一个SqlSession(打开了一个数据库链接)
        SqlSession sqlSession = sqlSessionFactory.openSession();

        // 使用SqlSession来获得Mapper对象
        Cursor<TbInfo> cursor = sqlSession.getMapper(TbInfoMapper.class).scan(limit);

        List<TbInfo> result = new ArrayList<>();
        cursor.forEach(item -> {
            result.add(item);
        });

        return Result.OK(result);
    }

    @GetMapping("/getGeneralInfo")
    public Result<?> getGeneralInfo(@RequestParam(name = "limit") int limit) throws Exception {
        LambdaQueryWrapper<TbInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.last(" limit " + limit);
        List<TbInfo> result = this.tbInfoService.list(wrapper);
        return Result.OK(result);
    }

    /*
    * <code>

    * 查询方式   |  用时  |  总数  |   大小
    * 流式查询  |  29ms |  2002  |   101.55kb
    * 常规查询  |  38ms |  2002  |   101.55kb
    * --------------------------------------------
    * 流式查询  |  61ms |  4002  |   203.84kb
    * 常规查询  |  69ms |  4002  |   203.84kb
    * </code>
    *
    *
    *
    *
    * */


}
